import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';

import '../../helper.dart';
import '../../router.dart';
import 'trolley_state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class TrolleyLogic extends GetxController {
  TrolleyState state = TrolleyState();
  var cartItemsNum = RxInt(0);

  @override
  void onInit() {
    super.onInit();
    // 测试用
    if (SpUtil.getString('userNumId') != '' &&
        SpUtil.getString('userNumId') != null) {
      var params = {
        "mobile": null,
        "usr_num_id": SpUtil.getString('userNumId'),
        'access_token': SpUtil.getString('token'),
      };
      Api.searchMember(params).listen((event) {
        print(params);
        state.orderMemberData = event;
        update();
      });
    }
  }

  @override
  void onReady() {
    super.onReady();
    // print('1111111111111111111111');
    // state.edit = false;
    // if (SpUtil.getInt('empeNumId') != '') {
    //   cartGoodsData();
    // getrecommendGoods();
    // }
  }

  // void setSex(int sex) {
  //   state.sendType = sex;
  //   update();
  // }
  //
  // void selectStatus(int index) {
  //   if (index == 2) {
  //     Get.toNamed(RouteConfig.orderDeposit);
  //   }
  //   state.statusIndex = index;
  //   update();
  // }

  //购物车商品数据
  void cartGoodsData(params) {
    Api.cartGoodsData(params).listen((event) {
      print('event["multi_shop_items"]');
      print(event["multi_shop_items"]);
      if (event["multi_shop_items"] == null) {
        state.cartDataList = [];
      } else {
        state.cartDataList = event["multi_shop_items"];
      }
      state.cartData = event;

      getclickNum();
      // MainAppLogics.getCartNum();
      getshopTag();
      if (event["multi_shop_items"] != null) {
        getSxGoodList(event["multi_shop_items"][0]);
      }
      update();
    });
  }

  //清除失效商品
  clearsxArr() {
    List cart_idarr = [];
    state.sxGoodList.forEach((element) {
      cart_idarr.add(element['cart_id']);
    });
    var params = {
      'access_token': SpUtil.getString('token'),
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "cart_id": getTaskScreen(cart_idarr) //多个用逗号隔开
    };
    print(params);

    Api.cartDelete(params).listen((event) {
      if (event["code"] == 0) {
        state.sxGoodList.clear();
        update();
      }
    });
  }

// 进入商品详情
  void enterGoodsDetail(style_num_id, ec_style_num_id, cat_id,
      default_item_num_id, shop_num_id, is_pre_sale) {
    String itemNumId = default_item_num_id.toString();
    String styleNumId = style_num_id.toString();
    String ecStyleNumId = ec_style_num_id.toString();
    Get.toNamed(RouteConfig.goodsDetail, arguments: {
      'itemNumId': itemNumId,
      'styleNumId': styleNumId,
      'shopId': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'].toString(),
      'ecStyleNumId': ecStyleNumId,
      'typeIndex': is_pre_sale,
    });
  }

  ///获取失效商品
  getSxGoodList(data) {
    state.sxGoodList = [];
    // if(data['stock_out_list'].length)
    if (data['stock_out_list'].length > 0 && data['stock_out_list'] != null) {
      data['stock_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['sold_out_list'].length > 0 && data['sold_out_list'] != null) {
      data['sold_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['without_list'].length > 0 && data['without_list'] != null) {
      data['without_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['delivery_out_list'].length > 0 &&
        data['delivery_out_list'] != null) {
      data['delivery_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['shop_close_list'].length > 0 && data['shop_close_list'] != null) {
      data['shop_close_list'].forEach((element) {
        state.sxGoodList.add(state.sxGoodList);
      });
    }
    print('失效商品');
    print(state.sxGoodList);
    update();
  }

  getrecommendGoodsList() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "use_platform": 2,
        "is_recommend": 1,
        // "shop_id": shopId,
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "adr_num_id": addressInfo["adr_num_id"],
        "page_no": 1,
        "page_size": 10,
        "access_token": SpUtil.getString('token')
      };
      Api.recommendGoods(params).listen((event) {
        if (event["code"] == 0) {
          // state.recommendGoods = event;
          update();
        }
      });
    });
  }

  ///获取购物车角标
  getshopTag() {
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);
    if (shopInfo == null) return;
    var params = {
      // SpUtil.putInt('storeShopNum', expressMap['ec_shop_num_id']); //  门店id
      "from_where": 1,
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": shopInfo['shop_id'],
      "super_ec_shop_num_id": 100049001,
      "use_platform": "2"
    };
    Api.shopTag(params).listen((event) {
      if (event["code"] == 0) {
        event['cart_norm_tag'].forEach((f) {
          if (f['tag_type'] == 'promotion_cat') {
            state.promotion_cat = f;
          }
          if (f['tag_type'] == 'activity_cat') {
            state.activity_cat = f;
          }
        });

        List arr = state.promotion_cat['fillet'].split(",");
        List arr2 = state.promotion_cat['fillet'].split(",");
        for (var i = 0; i < arr.length; i++) {
          state.angle[i] = double.parse(arr[i]);
        }
        for (var j = 0; j < arr.length; j++) {
          state.cxangle[j] = double.parse(arr2[j]);
        }
        print('111111111111111111111111111111111111111111111111111111111');
        print(state.angle);
        update();
      }
    });
  }

  ///获取商品规格
  void goodsSpecifications(data) {
    var params = {
      "shop_id": data["ec_shop_num_id"],
      "style_num_id": data["style_num_id"],
      "ec_style_num_id": data["ec_style_num_id"],
      "default_item_num_id": data["item_num_id"],
    };
    //获取选择商品规格数据
    Api.goodsSpecifications(params).listen((event) {
      state.goodsSpecificationsData = event["spec"];
      //默认选中项
      var idNum = event["spec"]["default_prop_id"].toString();
      // //默认选中商品图片
      state.goodsSpecificationsImageData =
          event["spec"]["spec_item"][idNum]["image_default_id"];
      // //默认选中商品规格标题
      state.goodsSpecificationsTitleData =
          event["spec"]["spec_item"][idNum]["item_name"];
      //商品规格列表
      // List data = event["spec"]["specs"]["specs"];
      //商品规格列表数据
      state.selectSpecifications = event["spec"]["default_prop_id"].toString();
      // data.forEach((element) {
      //   state.selectSpecifications.add(element['spec_values'][0]['spec_value_id']);
      // });
      // String selectSpecifications = state.selectSpecifications.join('_').toString();
      state.sumParic =
          event["spec"]["spec_item"][state.selectSpecifications]["price"];

      update();
    });
  }

  //删除商品
  cartDelete(params) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      Api.cartDelete(params).listen((event) {
        if (event["code"] == 0) {
          var params = {
            "usr_num_id": SpUtil.getInt('empeNumId'),
            "use_platform": 2,
            "prv_num_id": addressInfo['prv_num_id'],
            "city_num_id": addressInfo['city_num_id'],
            "city_area_num_id": addressInfo['city_area_num_id'],
            "town_num_id": addressInfo['town_num_id'],
            "maplocation_x": addressInfo['maplocation_x'],
            "maplocation_y": addressInfo['maplocation_y'],
            "adr_num_id": addressInfo["adr_num_id"],
            'access_token': SpUtil.getString('token'),
          };
          cartGoodsData(params);

          update();
        }
      });
    });
  }

  //多规格切换
  specCart(asum) {
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "cart_id": state.cart_id,
      // 'inv_from_type': logic.state.sendType == 1
      //     ? 3
      //     : null, //个人仓时传3，非个人仓传2或null
      'access_token': SpUtil.getString('token'),
    };
    Api.cartDelete(params).listen((event) {
      if (event["code"] == 0) {
        print('购物行为2');
        var params1 = {
          "use_platform": 2,
          //app
          "usr_num_id": SpUtil.getInt('empeNumId'),
          'access_token': SpUtil.getString('token'),
          "channel_num_id": 99,
          //订单渠道：小程序 98，App 99
          "ec_shop_num_id": state.ec_shop_num_id,
          //店铺编码
          "item_num_id": state.item_num_id,
          //商品编码
          "quantity": asum,
          //数量
          'inv_from_type': 2,
          // 'spec_value_id': logic.state.selectSpecifications,
          // 'spec_value_id':
          //个人仓时传3，非个人仓传2或null
          "style_num_id": state.goodsSpecificationsData["spec_item"]
              [state.selectSpecifications]["ec_style_num_id"],
          //款式编码
          "ec_style_num_id": state.goodsSpecificationsData["spec_item"]
              [state.selectSpecifications]["ec_style_num_id"],
          //唯一款式编码
        };
        print('选着的多规格');
        // print(logic.state.selectSpecifications);
        // print(params1);
        print(state.item_num_id);
        addShoppingCart(params1);

        update();
      }
    });
  }

  //选中商品加入购物车
  void addShoppingCart(params) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      Api.addShoppingCart(params).listen((event) {
        //添加成功获取购物车商品数量
        if (event["code"] == 0) {
          toast("添加成功");
          var params = {
            "usr_num_id": SpUtil.getInt('empeNumId'),
            "use_platform": 2,
            "prv_num_id": addressInfo['prv_num_id'],
            "city_num_id": addressInfo['city_num_id'],
            "city_area_num_id": addressInfo['city_area_num_id'],
            "town_num_id": addressInfo['town_num_id'],
            "maplocation_x": addressInfo['maplocation_x'],
            "maplocation_y": addressInfo['maplocation_y'],
            "adr_num_id": addressInfo["adr_num_id"],
            'access_token': SpUtil.getString('token'),
          };
          cartGoodsData(params);
          Get.back(result: true);
        } else {
          toast(event['message']);
        }
      });
    });
  }

  //购物车商品全选

  void cartChoose(params) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      Api.cartChoose(params).listen((event) {
        //添加成功获取购物车商品数量
        var params = {
          "usr_num_id": SpUtil.getInt('empeNumId'),
          "prv_num_id": addressInfo['prv_num_id'],
          "city_num_id": addressInfo['city_num_id'],
          "city_area_num_id": addressInfo['city_area_num_id'],
          "town_num_id": addressInfo['town_num_id'],
          "maplocation_x": addressInfo['maplocation_x'],
          "maplocation_y": addressInfo['maplocation_y'],
          "adr_num_id": addressInfo["adr_num_id"],
          'access_token': SpUtil.getString('token'),
        };
        cartGoodsData(params);
      });
    });
  }

  //购物车编辑修改数量
  void cartItemEdit(id, checked, sum) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "usr_num_id": SpUtil.getInt('empeNumId'),
        "use_platform": 2,
        // "emp_num_id": SpUtil.getInt('empeNumId'),
        "cart_params": [
          {"cart_id": id, "is_checked": checked, "total_quantity": sum}
        ],
        'access_token': SpUtil.getString('token'),
        "channel_num_id": 99
      };
      print(params);
      Api.cartItemEdit(params).listen((event) {
        if (event["code"] == 0) {
          var params = {
            "usr_num_id": SpUtil.getInt('empeNumId'),
            "use_platform": 2,
            "prv_num_id": addressInfo['prv_num_id'],
            "city_num_id": addressInfo['city_num_id'],
            "city_area_num_id": addressInfo['city_area_num_id'],
            "town_num_id": addressInfo['town_num_id'],
            "maplocation_x": addressInfo['maplocation_x'],
            "maplocation_y": addressInfo['maplocation_y'],
            "adr_num_id": addressInfo["adr_num_id"],
            'access_token': SpUtil.getString('token'),
          };
          cartGoodsData(params);
          update();
        }
      });
    });
  }

  //
  //获取自提点列表数据
  void selfHelpAddress() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "adr_num_id": addressInfo["adr_num_id"],

        "page": 1,
        "page_size": 10,
        'user_type': 1, //用户类型:1网格员,2KOC
        'usr_num_id': SpUtil.getInt('empeNumId')
      };
      Api.selfHelpAddress(params).listen((event) {
        state.selfHelpAddressList = event["sub_unit_shop_list"];
        update();
      });
    });
  }

  ///设置是删除还是去结算
  setDel() {
    state.edit = !state.edit;
    update();
  }

  ///批量删除
  allDed() {
    List<dynamic> list = [];
    if (state.cartData["checkedall"] != -1 &&
        state.cartDataList != null &&
        state.cartDataList.length > 0) {
      for (var i = 0; i < state.cartData["multi_shop_items"].length; i++) {
        for (var k = 0;
            k < state.cartData["multi_shop_items"][i]['cart_item_list'].length;
            k++) {
          for (var j = 0;
              j <
                  state
                      .cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items']
                      .length;
              j++) {
            // print( state.cartData["multi_shop_items"][i]['cart_item_list'][k]['items'][j]['is_checked']);
            if (state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                    ['items'][j]['is_checked'] ==
                1) {
              list.add(state.cartData["multi_shop_items"][i]['cart_item_list']
                      [k]['items'][j]['cart_id']
                  .toString());
            }
          }
        }
      }
    }

    var params = {
      // "usr_num_id": state.orderMemberData["empeNumId"],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,
      "cart_id": getTaskScreen(list)
    };
    cartDelete(params);
  }

  ///或许选择的数量

  getclickNum() {
    var num = 0;
    var cardItems = 0;
    // state.cartData["checkedall"] != -1 &&
    if (state.cartDataList != null && state.cartDataList.length > 0) {
      for (var i = 0; i < state.cartData["multi_shop_items"].length; i++) {
        for (var k = 0;
            k < state.cartData["multi_shop_items"][i]['cart_item_list'].length;
            k++) {
          //         print('state.cartData');
          // print(state.cartData["multi_shop_items"][i]['cart_item_list'][k]);
          for (var j = 0;
              j <
                  state
                      .cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items']
                      .length;
              j++) {
            cardItems++;
            // cardItems = cardItems + state.cartData["multi_shop_items"][i]['cart_item_list'][k]['items'][j]['quantity'].toInt();
            // print( state.cartData["multi_shop_items"][i]['cart_item_list'][k]['items'][j]['is_checked']);
            if (state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                    ['items'][j]['is_checked'] ==
                1) {
              num = num +
                  state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items'][j]['quantity']
                      .toInt();
              // num++;
            }
          }
        }
      }
    }
    cartItemsNum.value = cardItems;
    state.clickNum = num;
    update();
  }

  ///结算
  GoSettlement() {
    if (state.cartData["checkedall"] != -1 &&
        state.cartDataList != null &&
        state.cartDataList.length > 0) {
      // Get.toNamed(RouteConfig.orderSettlement, arguments: {
      //   'type': state.sendType,
      //   'orderMemberData': state.orderMemberData
      // }).then((value) {
      //   onReady();
      //   update();
      // });
      // // }
    } else {
      toast("请先选择商品");
      return;
    }
  }

  ///数组转字符串
  String getTaskScreen(List list) {
    List tempList = [];
    String str = '';
    list.forEach((f) {
      tempList.add(f);
    });

    tempList.forEach((f) {
      if (str == '') {
        str = "$f";
      } else {
        str = "$str" "," "$f";
      }
    });

    return str;
  }

  getrecommendGoods() {
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);
    if (shopInfo == null) return;
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,

      "is_recommend": 1, //死值,推荐商品
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": shopInfo['shop_id'],
      "page_no": 1,
      "page_size": 10,
      "order_by": "sold_quantity desc"
    };
    state.TJlist = [];
    print('商品id');
    Api.recommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        if (event['lists'] != null && event['lists'].length > 0) {
          state.TJlist = event['lists'];
          List listId = [];
          state.TJlist.forEach((element) {
            listId.add(element['default_item_num_id']);
          });

          var params = {
            "shop_id": shopInfo['shop_id'],
            "super_ec_shop_num_id": 100049001,
            "use_platform": "2",
            'item_num_id_list': listId
          };

          Api.shopTag(params).listen((event) {
            if (event["code"] == 0) {
              for (var i = 0; i < event['tag_list'].length; i++) {
                state.TJlist[i]['norm_tag_models'] =
                    event['tag_list'][i]['norm_tag_models'];
              }
              print('商品id1');
              for (var i = 0; i < state.TJlist.length; i++) {
                print(state.TJlist[i]['norm_tag_models']);
              }

              update();
            }
          });
        }
      }
    });
  }

  getMoney(data) {
    String priceStr = '', oldPriceStr = '', tiShi = '';
    bool oldBool = false;
    if (data['is_seckill'] == 1) {
      // 秒杀商品
      priceStr = data['price'].toString();
      oldBool = data['mkt_price'] > data['price']; // 显示旧价格
      oldPriceStr = data['mkt_price'].toString();
    } else if (data['is_pre_sale'] == 1) {
      priceStr = data['price'].toString();
      oldBool = data['mkt_price'] > data['price']; // 显示旧价格
      oldPriceStr = data['mkt_price'].toString();
    } else {
      if (data['expect_price'] > 0) {
        priceStr = '${data['expect_price'].toString()}';
        tiShi = '折后';
        oldBool = data['mkt_price'] > data['expect_price']; // 显示旧价格
        oldPriceStr = data['mkt_price'].toString();
      } else {
        priceStr = data['price'].toString();
        oldBool = data['mkt_price'] > data['price']; // 显示旧价格
        oldPriceStr = data['mkt_price'].toString();
      }
    }
    return [priceStr, oldPriceStr];
  }

  // 添加购物车
  void bottomaddShoppingCart({
    String ec_shop_num_id,
    String item_num_id,
    String style_num_id,
    String ec_style_num_id,
  }) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "use_platform": 2, //平台
        "usr_num_id": SpUtil.getInt('empeNumId'), //会员ID
        "emp_num_id": 0, //操作员ID,移动端无属性,默认传0
        "channel_num_id": 99, //订单渠道：小程序 98，App 99
        "quantity": 1.0, //数量
        "ec_shop_num_id": ec_shop_num_id, //店铺编码
        "item_num_id": item_num_id, //商品编码
        "style_num_id": style_num_id, //款式编码
        "ec_style_num_id": ec_style_num_id, //款式唯一编码
        'access_token': SpUtil.getString('token'),
      };
      Api.addShoppingCart(params).listen((event) {
        if (event['code'] == 0) {
          // MainAppLogics.getCartNum();
          var params = {
            "usr_num_id": SpUtil.getInt('empeNumId'),
            "use_platform": 2,
            "prv_num_id": addressInfo['prv_num_id'],
            "city_num_id": addressInfo['city_num_id'],
            "city_area_num_id": addressInfo['city_area_num_id'],
            "town_num_id": addressInfo['town_num_id'],
            "maplocation_x": addressInfo['maplocation_x'],
            "maplocation_y": addressInfo['maplocation_y'],
            "adr_num_id": addressInfo["adr_num_id"],
            'access_token': SpUtil.getString('token'),
          };
          cartGoodsData(params);
          toast('添加成功');
        } else {
          toast(event['message']);
        }
      });
    });
  }
}
